# sb_sale/models/account_checking_invoice_wizard.py

from odoo import models, fields, api
from odoo.exceptions import UserError


class SBMiscInvoiceWizard(models.TransientModel):
    _name = 'sb.misc.invoice.wizard'
    _description = 'Create Miscellaneous Invoice for Account Checking'

    account_checking_id = fields.Many2one(
        'sb.account.checking',
        string='Account Checking Record',
        required=True,
        ondelete='cascade',
        help="The account checking record for which to create the miscellaneous invoice."
    )
    customer_id = fields.Many2one(
        'res.partner',
        string='Customer',
        compute='_compute_customer_id',
        store=True,
        readonly=True,
        help="Customer associated with the account checking record."
    )
    invoice_date = fields.Date(
        string='Invoice Date',
        required=True,
        default=fields.Date.context_today,
        help="Date of the new miscellaneous invoice."
    )
    invoice_line_ids = fields.One2many(
        'sb.misc.invoice.line.wizard',  # <--- 模块名已简化
        'wizard_id',
        string='Invoice Lines',
        copy=True,
        help="Details of the service products to be included in the invoice."
    )
    note = fields.Text(string='Note', help="Internal note for the miscellaneous invoice.")
    currency_id = fields.Many2one('res.currency', related='account_checking_id.currency_id', readonly=True, help="Currency of the account checking record.")

    @api.depends('account_checking_id')
    def _compute_customer_id(self):
        for rec in self:
            rec.customer_id = rec.account_checking_id.customer.id

    def action_create_invoice(self):
        """
        根据向导中的信息创建一张新的杂项客户发票。
        """
        self.ensure_one()

        if not self.invoice_line_ids:
            raise UserError("请至少添加一行发票明细。")

        # 准备发票头数据
        invoice_vals = {
            'partner_id': self.customer_id.id,
            'move_type': 'out_invoice',  # 客户发票
            'invoice_date': self.invoice_date,
            'state': 'draft',  # 先创建草稿状态，后续可手动确认
            'sb_checking_id': self.account_checking_id.id,  # 关联到对账单
            'invoice_origin': self.account_checking_id.name,  # 记录来源
            'narration': self.note,  # 备注
            'currency_id': self.currency_id.id,  # 使用对账单的货币

        }

        # 创建发票行数据
        invoice_lines_vals = []
        for line in self.invoice_line_ids:
            if not line.product_id:
                raise UserError("发票行中必须选择产品。")

            # 获取产品默认的账户和税
            account_id = line.product_id.property_account_income_id or line.product_id.categ_id.property_account_income_categ_id
            if not account_id:
                raise UserError(f"产品 '{line.product_id.name}' 没有配置收入科目。")

            taxes = line.product_id.taxes_id.filtered(lambda t: t.company_id == self.env.company)
            # 应用客户的税务定位（fiscal position）来计算正确的税
            fiscal_position = self.customer_id.property_account_position_id
            if fiscal_position:
                taxes = fiscal_position.map_tax(taxes)

            invoice_lines_vals.append((0, 0, {
                'product_id': line.product_id.id,
                'quantity': line.quantity,
                'price_unit': line.price_unit,
                'name': line.product_id.name,  # 发票行名称
                'account_id': account_id.id,
                'tax_ids': [(6, 0, taxes.ids)],  # 关联税
            }))

        invoice_vals['invoice_line_ids'] = invoice_lines_vals

        # 创建发票
        new_invoice = self.env['account.move'].create(invoice_vals)
        self.account_checking_id.write({'misc_ids': [(4, new_invoice.id)]})
        # 返回动作，打开新创建的发票
        # return {
        #     'type': 'ir.actions.act_window',
        #     'name': 'New Miscellaneous Invoice',
        #     'res_model': 'account.move',
        #     'view_mode': 'form',
        #     'res_id': new_invoice.id,
        #     'target': 'current',
        # }
        return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }


class SBMiscInvoiceLineWizard(models.TransientModel):  # <--- 模块名已简化
    _name = 'sb.misc.invoice.line.wizard'
    _description = 'Miscellaneous Invoice Line for Wizard'

    wizard_id = fields.Many2one(
        'sb.misc.invoice.wizard',
        string='Invoice Wizard',
        required=True,
        ondelete='cascade'
    )
    product_id = fields.Many2one(
        'product.product',
        string='Service Product',
        required=True,
        domain=[('type', '=', 'service')],
        help="Select a service product for the invoice line."
    )
    quantity = fields.Float(
        string='Quantity',
        required=True,
        default=1.0,
        help="Quantity of the service product."
    )
    price_unit = fields.Float(
        string='Unit Price',
        required=True,
        help="Unit price of the service product."
    )
